package com.yb.livewykt.vm

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.yb.livewykt.bean.ErrorMsg
import com.yb.livewykt.net.Result
import com.yb.livewykt.net.RetrofitUtil
import com.yb.livewykt.net.UserApi
import com.yb.livewykt.util.netError
import com.yb.livewykt.util.responseSuccessCode
import com.yb.livewykt.util.responseTokenFailedCode
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.StatusCode
import com.netease.nimlib.sdk.auth.AuthServiceObserver
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

open class BaseViewModel(application: Application) : AndroidViewModel(application) {

    protected val TAG = this.javaClass.simpleName

    val userApi = RetrofitUtil.get().createService(UserApi::class.java)
    val tokenFiled = MutableLiveData<Boolean>()
    val showErrorMsg = MutableLiveData<ErrorMsg>()
    var wyLoginMonitor = MutableLiveData<Boolean>()
    init {
        tokenFiled.value = false
    }

    fun loginStatue(boolean: Boolean){
        NIMClient.getService(AuthServiceObserver::class.java).observeOnlineStatus({
            //if (it.wontAutoLogin()) isOffLineLiveData.value = true
            if (it == StatusCode.LOGINED) wyLoginMonitor.value = true
            if (it == StatusCode.UNLOGIN || it == StatusCode.PWD_ERROR || it == StatusCode.VER_ERROR) wyLoginMonitor.value =
                false
        }, boolean)
    }


    fun <T> launch(
        block: suspend CoroutineScope.() -> Result<T>,
        liveData:MutableLiveData<T>
    ){
        var result:Result<T>? = null
        viewModelScope.launch {
            try {
                withContext(Dispatchers.IO){
                    result = block()
                }
                Log.d(TAG, "launch: ${result.toString()}")
                when(result?.code!!){
                    responseSuccessCode ->{
                        liveData.value = result?.data!!
                    }
                    responseTokenFailedCode -> {
                        tokenFiled.value = true
                    }
                    else ->{
                        showErrorMsg.value = ErrorMsg(result?.code!!,result?.msg!!)
                    }
                }
            }catch (e:Exception){
                showErrorMsg.value = netError()
                e.printStackTrace()
            }
        }

    }

    fun  launch(
        block:suspend CoroutineScope.() -> Unit
    ) {
        viewModelScope.launch {
            try {
                withContext(Dispatchers.IO){
                    block()
                }
            }catch (e:Exception){
                e.printStackTrace()
            }
        }

    }

}